<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="48px">
      <el-form-item label="商品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位ID" prop="warehouseLocationId">
        <el-input
          v-model="queryParams.warehouseLocationId"
          placeholder="请输入库位ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前库存数量" prop="currentQuantity" align="center" label-width="85px" > 
        <el-input
          v-model="queryParams.currentQuantity"
          placeholder="请输入当前库存数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="可用数量" prop="availableQuantity"  label-width="60px" >
        <el-input
          v-model="queryParams.availableQuantity"
          placeholder="请输入可用数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="已分配数量" prop="allocatedQuantity" label-width="75px" >
        <el-input
          v-model="queryParams.allocatedQuantity"
          placeholder="请输入已分配数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
  
      <el-form-item label="更新人" prop="updatedBy">
        <el-input
          v-model="queryParams.updatedBy"
          placeholder="请输入更新人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['scm:inventory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['scm:inventory:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['scm:inventory:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['scm:inventory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 浏览模式标签区 -->
    <div style="margin-bottom: 12px;">
      <el-tag
        :type="browseMode === 'location' ? 'success' : 'info'"
        effect="dark"
        style="cursor:pointer;margin-right:8px;"
        @click="handleBrowseModeChange('location')"
      >按库位浏览</el-tag>
      <el-tag
        :type="browseMode === 'product' ? 'success' : 'info'"
        effect="dark"
        style="cursor:pointer;margin-right:8px;"
         @click="handleBrowseModeChange('product')"
      >按库品浏览</el-tag>
      <el-tag
        :type="browseMode === 'order' ? 'success' : 'info'"
        effect="dark"
        style="cursor:pointer;"
        @click="handleBrowseModeChange('order')"
      >按订单浏览</el-tag>
    </div>


    <el-table v-if="browseMode === 'location'" v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 展开行 -->
      <el-table-column type="expand">
        <template #default="props">
          <el-table
            :data="props.row.historyList"
            style="width: 100%;font-size: 12px;"
            size="mini"
            border
          >
            <el-table-column label="序列" prop="id" width="60" />
            <el-table-column label="订单号" prop="orderCode" width="150"/>
            <el-table-column label="操作类型" prop="changeType"  width="100">
              <template #default="scope">
                <!-- 显示类型文本 -->
                <span>
                  {{ scope.row.changeType === 1 ? '入库' : scope.row.changeType === 2 ? '出库' : scope.row.changeType }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="产品信息">
              <template #default="scope">
                {{ [scope.row.productName, scope.row.drawingVersion, scope.row.drawingNumberModel].filter(Boolean).join('|') }}
              </template>
            </el-table-column>
            <el-table-column label="订单总数" prop="orderTotalQuantity" />
            <el-table-column label="变动前数量" prop="beforeQuantity" />
            <el-table-column label="变动数量" prop="changeQuantity" />
            <el-table-column label="变动后数量" prop="afterQuantity" />
            <el-table-column label="订单完成数量" prop="orderQuantityInLib" />
            <el-table-column label="订单未完成量" prop="orderQuantityNotInLib" />
            <el-table-column label="变动时间" prop="createdAt" />
          </el-table>
        </template>
      </el-table-column>

      <!-- <el-table-column label="库存主键" align="center" prop="id" /> -->
      <el-table-column label="库位ID" align="center" prop="warehouseLocationId" />
      <el-table-column label="库位" align="center" prop="warehouseLocationName" />
      <el-table-column label="商品" align="center" prop="productName" />
      <el-table-column label="商品版本" align="center" width="150">
        <template #default="scope">
          {{ [scope.row.productDrawing, scope.row.productVersion, scope.row.productInnerVersion].filter(Boolean).join('&') }}
        </template>
      </el-table-column>
  
      <el-table-column label="当前库存数量" align="center" prop="currentQuantity" />
      <el-table-column label="可用数量" align="center" prop="availableQuantity" />
      <el-table-column label="已分配数量" align="center" prop="allocatedQuantity" />
      <el-table-column label="最低库存预警值" align="center" prop="minimumStock" />
      <el-table-column label="最高库存预警值" align="center" prop="maximumStock" />
      <el-table-column label="库存状态" align="center" prop="inventoryStatus" />
      <!-- <el-table-column label="最后更新时间" align="center" prop="lastUpdateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastUpdateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="更新人" align="center" prop="updatedBy" />
      <el-table-column label="更新人ID" align="center" prop="updatedById" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['scm:inventory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['scm:inventory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 按库品浏览 -->
    <el-table
      v-if="browseMode === 'product'"
      v-loading="loading"
      :data="productInventoryList"
      @selection-change="handleSelectionChange"
    >
      <!-- 按库品浏览的表格内容 -->
      <el-table-column type="selection" width="55" align="center" />
      <!-- 展开行 -->
     
      <el-table-column type="expand">
        <template #default="props">
          <el-table
            :data="props.row.historyList"
            style="width: 100%;font-size: 12px;"
            size="mini"
            border
          >
            <el-table-column label="序列" prop="id" />
            <el-table-column label="订单号" prop="orderCode" />
            <el-table-column label="操作类型" prop="changeType">
              <template #default="scope">
              
                <span>
                  {{ scope.row.changeType === 1 ? '入库' : scope.row.changeType === 2 ? '出库' : scope.row.changeType }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="产品信息">
              <template #default="scope">
                {{ [scope.row.productName, scope.row.drawingVersion, scope.row.drawingNumberModel].filter(Boolean).join('|') }}
              </template>
            </el-table-column>
            <el-table-column label="库位" prop="warehouseLocationId" />
            <el-table-column label="订单总数" prop="orderTotalQuantity" />
            <el-table-column label="变动前数量" prop="beforeQuantity" />
            <el-table-column label="变动数量" prop="changeQuantity" />
            <el-table-column label="变动后数量" prop="afterQuantity" />
            <el-table-column label="订单在库数量" prop="orderQuantityInLib" />
            <el-table-column label="订单未在库数量" prop="orderQuantityNotInLib" />
            <el-table-column label="变动时间" prop="createdAt" />
          </el-table>
        </template>
      </el-table-column>
    


      <!-- <el-table-column label="库存主键" align="center" prop="id" /> -->
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="商品" align="center" prop="productName" />
       
      <el-table-column label="商品版本" align="center" width="150">
        <template #default="scope">
          {{ [scope.row.productDrawing, scope.row.productVersion, scope.row.productInnerVersion].filter(Boolean).join('&') }}
        </template>
      </el-table-column>
  
      <el-table-column label="当前库存数量" align="center" prop="currentQuantity" />
      <el-table-column label="可用数量" align="center" prop="availableQuantity" />
      <el-table-column label="已分配数量" align="center" prop="allocatedQuantity" />
      <el-table-column label="最低库存预警值" align="center" prop="minimumStock" />
      <el-table-column label="最高库存预警值" align="center" prop="maximumStock" />
      <el-table-column label="库存状态" align="center" prop="inventoryStatus" />
      <!-- <el-table-column label="最后更新时间" align="center" prop="lastUpdateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastUpdateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="更新人" align="center" prop="updatedBy" />
      <el-table-column label="更新人ID" align="center" prop="updatedById" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['scm:inventory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['scm:inventory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>

    </el-table>


    <!-- 按订单浏览 -->
    <el-table
      v-if="browseMode === 'order'"
      v-loading="loading"
      :data="orderInventoryList"
      @selection-change="handleSelectionChange"
    >
      <!-- 按订单浏览的表格内容 -->
    </el-table>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="库位ID" prop="warehouseLocationId">
          <el-input v-model="form.warehouseLocationId" placeholder="请输入库位ID" />
        </el-form-item>
        <el-form-item label="当前库存数量" prop="currentQuantity">
          <el-input v-model="form.currentQuantity" placeholder="请输入当前库存数量" />
        </el-form-item>
        <el-form-item label="可用数量" prop="availableQuantity">
          <el-input v-model="form.availableQuantity" placeholder="请输入可用数量" />
        </el-form-item>
        <el-form-item label="已分配数量" prop="allocatedQuantity">
          <el-input v-model="form.allocatedQuantity" placeholder="请输入已分配数量" />
        </el-form-item>
        <el-form-item label="最低库存预警值" prop="minimumStock">
          <el-input v-model="form.minimumStock" placeholder="请输入最低库存预警值" />
        </el-form-item>
        <el-form-item label="最高库存预警值" prop="maximumStock">
          <el-input v-model="form.maximumStock" placeholder="请输入最高库存预警值" />
        </el-form-item>
        <!-- <el-form-item label="最后更新时间" prop="lastUpdateTime">
          <el-date-picker clearable
            v-model="form.lastUpdateTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择最后更新时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新人" prop="updatedBy">
          <el-input v-model="form.updatedBy" placeholder="请输入更新人" />
        </el-form-item>
        <el-form-item label="更新人ID" prop="updatedById">
          <el-input v-model="form.updatedById" placeholder="请输入更新人ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventory, getInventory, delInventory, addInventory, updateInventory } from "@/api/scm/scmInventory";
import { listLog } from "@/api/scm/scmInventoryLog";
 
 
export default {
  name: "Inventory",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      inventoryList: [],
      productInventoryList: [],
      orderInventoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        warehouseLocationId: null,
        currentQuantity: null,
        availableQuantity: null,
        allocatedQuantity: null,
        minimumStock: null,
        maximumStock: null,
        inventoryStatus: null,
        lastUpdateTime: null,
        updatedAt: null,
        updatedBy: null,
        updatedById: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "商品ID不能为空", trigger: "blur" }
        ],
        warehouseLocationId: [
          { required: true, message: "库位ID不能为空", trigger: "blur" }
        ],
      },
      browseMode: 'location', // 默认按库位浏览
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 按库位*/
    getList() {
      this.loading = true;
        listInventory(this.queryParams).then(response => {
          console.log('listInventory response:1', response); // 立即打印
          const inventoryArr = response.rows || [];
          let count = 0;
          if (inventoryArr.length === 0) {
            this.inventoryList = [];
            this.total = response.total;
            this.loading = false;
            return;
          }
        inventoryArr.forEach((item, idx) => {
          // 用库位ID获取历史记录
          listLog({ warehouseLocationId: item.warehouseLocationId }).then(historyRes => {
            item.historyList = historyRes.rows || [];
            console.log('historyList for warehouseLocationId:', item.warehouseLocationId, item.historyList); // 打印每条记录的历史
            count++;
            // 所有历史数据获取完毕后再赋值
            if (count === inventoryArr.length) {
              this.inventoryList = inventoryArr;
              this.total = response.total;
              this.loading = false;
             
            }
          });
        });
      });

    },
    // 按产品浏览
    getProductList() {
      this.loading = true;
      listInventory(this.queryParams).then(response => {
        const inventoryArr = response.rows || [];
        // 按商品ID分组
        const productMap = {};
        inventoryArr.forEach(item => {
          const pid = item.productId;
          if (!productMap[pid]) {
            productMap[pid] = {
              ...item,
              historyList: [],
              currentQuantity: Number(item.currentQuantity) || 0,
              availableQuantity: Number(item.availableQuantity) || 0,
              allocatedQuantity: Number(item.allocatedQuantity) || 0
            };
          } else {
            productMap[pid].currentQuantity += Number(item.currentQuantity) || 0;
            productMap[pid].availableQuantity += Number(item.availableQuantity) || 0;
            productMap[pid].allocatedQuantity += Number(item.allocatedQuantity) || 0;
          }
        });

        // 获取每个唯一商品的库存历史
        const productList = Object.values(productMap);
        let count = 0;
        if (productList.length === 0) {
          this.productInventoryList = [];
          this.total = 0;
          this.loading = false;
          return;
        }
        productList.forEach((item, idx) => {
          listLog({ productId: item.productId }).then(historyRes => {
            item.historyList = historyRes.rows || [];
            count++;
            if (count === productList.length) {
              this.productInventoryList = productList;
              this.total = productList.length;
              this.loading = false;
            }
          });
        });
      });
    },
      // 按订单浏览
  getOrderList() {
    this.loading = true;
    listInventory(this.queryParams).then(response => {
      const inventoryArr = response.rows || [];
      let count = 0;
      if (inventoryArr.length === 0) {
        this.inventoryList = [];
        this.total = response.total;
        this.loading = false;
        return;
      }
      inventoryArr.forEach((item, idx) => {
        listLog({ warehouseLocationId: item.warehouseLocationId }).then(historyRes => {
          item.historyList = historyRes.rows || [];
          count++;
          if (count === inventoryArr.length) {
            this.inventoryList = inventoryArr;
            this.total = response.total;
            this.loading = false;
          }
        });
      });
    });
  },

 

  // 浏览模式切换时调用
  handleBrowseModeChange(mode) {
    this.browseMode = mode;
    if (mode === 'location') {
      this.getList();
    } else if (mode === 'product') {
      this.getProductList();
    }else if (mode === 'order') {
      this.getOrderList();
    }
    // 其它模式可继续扩展
  },



    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productId: null,
        warehouseLocationId: null,
        currentQuantity: null,
        availableQuantity: null,
        allocatedQuantity: null,
        minimumStock: null,
        maximumStock: null,
        inventoryStatus: null,
        lastUpdateTime: null,
        updatedAt: null,
        updatedBy: null,
        updatedById: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInventory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改【请填写功能名称】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function() {
        return delInventory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('scm/inventory/export', {
        ...this.queryParams
      }, `inventory_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
